import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';

class DetailCardInfoView extends StatefulWidget {
  final Function(bool) onToggleExpand;
  final String cardInfo;

  DetailCardInfoView({required this.onToggleExpand, required this.cardInfo});

  @override
  _DetailCardInfoViewState createState() => _DetailCardInfoViewState();
}

class _DetailCardInfoViewState extends State<DetailCardInfoView> {
  bool isExpanded = false;
  List<Tuple<String, String>> cardData = [];

  final Color titleBlueColor = Color(0xFF5D5FEE);
  final Color label2Color = Color(0xFF000000);
  final double cardSpacing = 12;
  final double cardSidePadding = 10;

  @override
  void initState() {
    super.initState();
    _parseCardInfo(widget.cardInfo);
  }

  // Parsing card info
  void _parseCardInfo(String cardInfo) {
    List<String> lines = cardInfo.split('\n');
    cardData = lines.map((line) {
      List<String> parts = line.trim().split(' ');
      if (parts.length == 1) {
        return Tuple('', parts[0]);
      } else if (parts.length >= 2) {
        return Tuple(parts[0], parts[1]);
      }
      return null;
    }).whereType<Tuple<String, String>>().toList();
  }

  void _toggleExpand() {
    setState(() {
      isExpanded = !isExpanded;
    });
    widget.onToggleExpand(isExpanded);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 15,right: 15,left: 15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15,right: 15,left: 15),
        child: Column(
           crossAxisAlignment: CrossAxisAlignment.start,
           children: [
          // Title
          Text(
            AppLocalizations.of(context)!.cardInfo,
            style: TextStyle(color: label2Color, fontSize: 16),
          ),
          SizedBox(height: 8),
          // Card Views
          ..._buildCardViews(),
          // Toggle button if necessary
          if (cardData.length > 3)
            Center(
              child: TextButton(
                onPressed: _toggleExpand,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      isExpanded ? AppLocalizations.of(context)!.shrink : AppLocalizations.of(context)!.clickToLoad,
                      style: TextStyle(color: Color(0xFF000000), fontSize: 16),
                    ),
                    SizedBox(width: 4),
                    Icon(
                      isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      color: Color(0xFF000000),
                      size: 28,
                    ),
                  ],
                ),
              ),
            ),
            if (cardData.length <= 3)
            SizedBox(height: 12),
        ],
      ),
      ),
    );
  }

  List<Widget> _buildCardViews() {
    List<Widget> cardViews = [];
    if (cardData.isEmpty) return cardViews;
    
    int maxCount = isExpanded ? cardData.length : 3;
    maxCount = maxCount > cardData.length ? cardData.length : maxCount;

    for (int i = 0; i < maxCount; i++) {
      final card = cardData[i];
      cardViews.add(_buildCardView(card.item1, card.item2));
    }

    return cardViews;
  }

Widget _buildCardView(String cardNumber, String password) {
  return Container(
    margin: EdgeInsets.only(top: cardSpacing),
    padding: EdgeInsets.symmetric(horizontal: cardSidePadding),
    decoration: BoxDecoration(
      color: Color(0xFFF5F5F5),
      borderRadius: BorderRadius.circular(15),
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Card number
        if (cardNumber.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 15),
            child: Row(
              children: [
                // 显示卡号文本，支持换行
                Expanded(
                  child: Text(
                    '卡号：$cardNumber',
                    style: TextStyle(fontSize: 16, color: label2Color),
                    maxLines: 3,  // 限制最大显示行数
                    overflow: TextOverflow.ellipsis,  // 超过部分显示省略号
                  ),
                ),
                // 固定在右侧的复制按钮
                SizedBox(
                  width: 60,
                  height: 24,
                  child: ElevatedButton(
                    onPressed: () => _copyToClipboard(cardNumber),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.transparent,
                      foregroundColor: Color(0xFF5D5FEE),
                      shadowColor: Colors.transparent,
                      padding: EdgeInsets.zero,
                      shape: RoundedRectangleBorder(
                        side: BorderSide(color: Color(0xFF5D5FEE)),
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Text(
                      AppLocalizations.of(context)!.copy,
                      style: TextStyle(color: Color(0xFF5D5FEE)),
                    ),
                  ),
                ),
              ],
            ),
          ),
        // 
        // Password
        Padding(
          padding: const EdgeInsets.only(top: 15,bottom: 15),
          child: Row(
            children: [
              // 显示卡密文本，支持换行
              Expanded(
                child: Text(
                  '卡密：$password',
                  style: TextStyle(fontSize: 16, color: Color(0xFF31383F)),
                  maxLines: 3,  // 限制最大显示行数
                  overflow: TextOverflow.ellipsis,  // 超过部分显示省略号
                ),
              ),
              // 固定在右侧的复制按钮
              SizedBox(
                width: 60,
                height: 24,
                child: ElevatedButton(
                  onPressed: () => _copyToClipboard(password),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    elevation: 0,
                    padding: EdgeInsets.zero,
                    shape: RoundedRectangleBorder(
                      side: BorderSide(color: Color(0xFF5D5FEE)),
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Text(
                    AppLocalizations.of(context)!.copy,
                    style: TextStyle(color: Color(0xFF5D5FEE)),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}


  void _copyToClipboard(String value) {
    Clipboard.setData(ClipboardData(text: value));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已复制到剪切板~')),
    );
  }
}

class Tuple<T1, T2> {
  final T1 item1;
  final T2 item2;

  Tuple(this.item1, this.item2);
}
        